package com.anos.smsfun.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

public class SearchSusgesstionsAdapter extends ArrayAdapter<String> implements
		Filterable {

	ArrayList<String> _items = new ArrayList<String>();
	ArrayList<String> orig = new ArrayList<String>();

	public SearchSusgesstionsAdapter(Context context, int resource,
			ArrayList<String> items) {
		super(context, resource, items);

		orig = items;
	}

	@Override
	public int getCount() {
		if (_items != null)
			return _items.size();
		else
			return 0;
	}

	@Override
	public String getItem(int arg0) {
		return _items.get(arg0);
	}

	@Override
	public Filter getFilter() {
		Filter filter = new Filter() {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {

				if (constraint != null)
					Log.d("Constraints", constraint.toString());
				FilterResults oReturn = new FilterResults();

				String temp;
				int counters = 0;
				if (constraint != null) {
					_items.clear();
					if (orig != null) {
						for (int i = 0; i < orig.size(); i++) {
							temp = orig.get(i).toString().toUpperCase();
							if (constraint.toString().length() <= temp.length()) {
								if (temp.indexOf(constraint.toString().trim()
										.toUpperCase()) != -1) {
									_items.add(orig.get(i));
									counters++;
								}
							}
						}
					}
					// Log.d("Result size:", String.valueOf(_items.size()));
					if (counters != 0) {
						// _items.clear();
						// _items = orig;
					}
					oReturn.values = _items;
					oReturn.count = _items.size();
				}
				return oReturn;
			}

			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				if (results != null && results.count > 0) {
					notifyDataSetChanged();
				} else {
					notifyDataSetInvalidated();
				}

			}

		};

		return filter;

	}

}
